package com.lw.leetcode.node;

/**
 * @Author liw
 * @Date 2021/4/29 9:50
 * @Version 1.0
 */
public class Connect {

    public static void main(String[] args) {
        Connect connect = new Connect();
        connect.connect(Node.getInstance());
    }

    public Node connect(Node root) {
        if (root == null || (root.left == null && root.right == null)) {
            return root;
        }
        if (root.left != null) {
            if (root.right != null) {
                root.left.next = root.right;
            } else {
                Node item = root.next;
                while (item != null) {
                    if (item.left != null) {
                        root.left.next = item.left;
                        break;
                    }
                    if (item.right != null) {
                        root.left.next = item.right;
                        break;
                    }
                    item = item.next;
                }
            }
        }
        if (root.right != null) {
            Node item = root.next;
            while (item != null) {
                if (item.left != null) {
                    root.right.next = item.left;
                    break;
                }
                if (item.right != null) {
                    root.right.next = item.right;
                    break;
                }
                item = item.next;
            }
        }
        connect(root.left);
        connect(root.right);
        return root;
    }
}
